package com.ly.web.controller.erp;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ly.heart.domain.dto.BranchSubTypeDto;
import com.ly.heart.domain.response.BranchSubTypeResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ly.common.annotation.Log;
import com.ly.common.core.controller.BaseController;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.enums.BusinessType;
import com.ly.heart.domain.BranchSubTypeEntity;
import com.ly.heart.service.IBranchSubTypeService;
import com.ly.common.utils.poi.ExcelUtil;
import com.ly.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 施工分部分项划分Controller
 *
 * @author wutao
 * @date 2024-06-10
 */
@Api(value = "type", tags = "施工分部分项划分")
@RestController
@RequestMapping("/heart/BranchSubType")
public class BranchSubTypeController extends BaseController {

    @Resource
    private IBranchSubTypeService branchSubTypeService;

    /**
     * 查询施工分部分项划分列表
     */
//    @PreAuthorize("@ss.hasPermi('heart:type:list')")
    @GetMapping("/list")
    @ApiOperation("查询施工分部分项划分列表")
    public AjaxResult list(BranchSubTypeDto branchSubType)
    {
        BranchSubTypeResponse branchSubTypeResponse = branchSubTypeService.selectBranchSubTypeList(branchSubType);
        return AjaxResult.success(branchSubTypeResponse);
    }

//    /**
//     * 导出施工分部分项划分列表
//     */
//    @PreAuthorize("@ss.hasPermi('heart:type:export')")
//    @Log(title = "施工分部分项划分", businessType = BusinessType.EXPORT)
//    @GetMapping("/export")
//    @ApiOperation("导出施工分部分项划分列表")
//    public AjaxResult export(BranchSubTypeEntity branchSubType)
//    {
//        List<BranchSubTypeEntity> list = branchSubTypeService.selectBranchSubTypeList(branchSubType);
//        ExcelUtil<BranchSubTypeEntity> util = new ExcelUtil<BranchSubTypeEntity>(BranchSubTypeEntity.class);
//        return util.exportExcel(list, "type");
//    }

    /**
     * 获取施工分部分项划分详细信息
     */
    @PreAuthorize("@ss.hasPermi('heart:type:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取施工分部分项划分详细信息")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(branchSubTypeService.selectBranchSubTypeById(id));
    }

    /**
     * 新增施工分部分项划分
     */
//    @PreAuthorize("@ss.hasPermi('heart:type:add')")
    @Log(title = "施工分部分项划分", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增施工分部分项划分")
    public AjaxResult add(@RequestBody BranchSubTypeEntity branchSubType)
    {
        return toAjax(branchSubTypeService.insertBranchSubType(branchSubType));
    }

    /**
     * 修改施工分部分项划分
     */
    @PreAuthorize("@ss.hasPermi('heart:type:edit')")
    @Log(title = "施工分部分项划分", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改施工分部分项划分")
    public AjaxResult edit(@RequestBody BranchSubTypeEntity branchSubType)
    {
        return toAjax(branchSubTypeService.updateBranchSubType(branchSubType));
    }

    /**
     * 删除施工分部分项划分
     */
    @PreAuthorize("@ss.hasPermi('heart:type:remove')")
    @Log(title = "施工分部分项划分", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @ApiOperation("删除施工分部分项划分")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(branchSubTypeService.deleteBranchSubTypeByIds(ids));
    }


    public static void main(String[] args) {
        String str = "[\n" +
                "        {\n" +
                "            \"createBy\": \"\",\n" +
                "            \"createTime\": \"2024-06-11 23:14:01\",\n" +
                "            \"updateBy\": \"\",\n" +
                "            \"params\": {},\n" +
                "            \"id\": \"20240611516254303816650752\",\n" +
                "            \"parentBranchName\": \"建筑智能化\",\n" +
                "            \"sonBranchName\": \"计算机机房工程\",\n" +
                "            \"subProject\": \"室内空调环境\",\n" +
                "            \"subProjectCode\": \"AI-J-001\",\n" +
                "            \"delFlag\": \"0\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"createBy\": \"\",\n" +
                "            \"createTime\": \"2024-06-11 23:14:59\",\n" +
                "            \"updateBy\": \"\",\n" +
                "            \"params\": {},\n" +
                "            \"id\": \"20240611516254546478108672\",\n" +
                "            \"parentBranchName\": \"建筑智能化\",\n" +
                "            \"sonBranchName\": \"计算机机房工程\",\n" +
                "            \"subProject\": \"服务器系统\",\n" +
                "            \"subProjectCode\": \"AI-J-002\",\n" +
                "            \"delFlag\": \"0\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"createBy\": \"\",\n" +
                "            \"createTime\": \"2024-06-11 23:15:25\",\n" +
                "            \"updateBy\": \"\",\n" +
                "            \"params\": {},\n" +
                "            \"id\": \"20240611516254655488069632\",\n" +
                "            \"parentBranchName\": \"建筑智能化\",\n" +
                "            \"sonBranchName\": \"计算机机房工程\",\n" +
                "            \"subProject\": \"路由交换系统\",\n" +
                "            \"subProjectCode\": \"AI-J-003\",\n" +
                "            \"delFlag\": \"0\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"createBy\": \"\",\n" +
                "            \"createTime\": \"2024-06-11 23:16:13\",\n" +
                "            \"updateBy\": \"\",\n" +
                "            \"params\": {},\n" +
                "            \"id\": \"20240611516254855837388800\",\n" +
                "            \"parentBranchName\": \"建筑智能化\",\n" +
                "            \"sonBranchName\": \"综合布线系统\",\n" +
                "            \"subProject\": \"缆线敷设和设备安装\",\n" +
                "            \"subProjectCode\": \"AI-Z-001\",\n" +
                "            \"delFlag\": \"0\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"createBy\": \"\",\n" +
                "            \"createTime\": \"2024-06-11 23:16:50\",\n" +
                "            \"updateBy\": \"\",\n" +
                "            \"params\": {},\n" +
                "            \"id\": \"20240611516255013719379968\",\n" +
                "            \"parentBranchName\": \"建筑电气\",\n" +
                "            \"sonBranchName\": \"电气照明安装\",\n" +
                "            \"subProject\": \"室内电气工程\",\n" +
                "            \"subProjectCode\": \"D-D-001\",\n" +
                "            \"delFlag\": \"0\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"createBy\": \"\",\n" +
                "            \"createTime\": \"2024-06-11 23:17:05\",\n" +
                "            \"updateBy\": \"\",\n" +
                "            \"params\": {},\n" +
                "            \"id\": \"20240611516255072997478400\",\n" +
                "            \"parentBranchName\": \"建筑电气\",\n" +
                "            \"sonBranchName\": \"电气照明安装\",\n" +
                "            \"subProject\": \"成套配电柜\",\n" +
                "            \"subProjectCode\": \"D-D-002\",\n" +
                "            \"delFlag\": \"0\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"createBy\": \"\",\n" +
                "            \"createTime\": \"2024-06-11 23:17:55\",\n" +
                "            \"updateBy\": \"\",\n" +
                "            \"params\": {},\n" +
                "            \"id\": \"20240611516255283597676544\",\n" +
                "            \"parentBranchName\": \"建筑消防\",\n" +
                "            \"sonBranchName\": \"消防主机系统\",\n" +
                "            \"subProject\": \"北大青鸟消防报警系统\",\n" +
                "            \"subProjectCode\": \"BD-FIRE-WARNING\",\n" +
                "            \"delFlag\": \"0\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"createBy\": \"\",\n" +
                "            \"createTime\": \"2024-06-11 23:18:32\",\n" +
                "            \"updateBy\": \"\",\n" +
                "            \"params\": {},\n" +
                "            \"id\": \"20240611516255438321356800\",\n" +
                "            \"parentBranchName\": \"建筑消防\",\n" +
                "            \"sonBranchName\": \"消防点位布防图\",\n" +
                "            \"subProject\": \"烟感消防点布防\",\n" +
                "            \"subProjectCode\": \"ANGAN-FIRE\",\n" +
                "            \"delFlag\": \"0\"\n" +
                "        }\n" +
                "    ]";


        List<BranchSubTypeEntity> javaList = JSON.parseArray(str).toJavaList(BranchSubTypeEntity.class);

        // 优化：直接构建最终的JSON结构
        List<JSONObject> result = javaList.stream()
                .collect(Collectors.groupingBy(BranchSubTypeEntity::getParentBranchName))
                .entrySet().stream()
                .map(parentEntry -> {
                    JSONObject parentJson = new JSONObject();
                    parentJson.put("name", parentEntry.getKey());
                    List<JSONObject> childrenJsonList = parentEntry.getValue().stream()
                            .collect(Collectors.groupingBy(BranchSubTypeEntity::getSonBranchName))
                            .entrySet().stream()
                            .map(childEntry -> {
                                JSONObject childJson = new JSONObject();
                                childJson.put("name", childEntry.getKey());
                                childJson.put("children", childEntry.getValue()); // 直接将实体列表作为"children"
                                return childJson;
                            })
                            .collect(Collectors.toList());

                    parentJson.put("children", childrenJsonList);
                    return parentJson;
                })
                .collect(Collectors.toList());

        System.out.println(result);



//        List<BranchSubTypeEntity> javaList = JSON.parseArray(str).toJavaList(BranchSubTypeEntity.class);
//
//        // 优化：一次遍历完成分组
//        Map<String, Map<String, List<BranchSubTypeEntity>>> collect = javaList.stream()
//                .collect(Collectors.groupingBy(BranchSubTypeEntity::getParentBranchName,
//                        Collectors.groupingBy(BranchSubTypeEntity::getSonBranchName)));
//
//        List<JSONObject> js = new ArrayList<>();
//        for (Map.Entry<String, Map<String, List<BranchSubTypeEntity>>> entry : collect.entrySet()) {
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("name", entry.getKey());
//
//            JSONObject childrenJson = new JSONObject();
//            for (Map.Entry<String, List<BranchSubTypeEntity>> subEntry : entry.getValue().entrySet()) {
//                JSONObject subJson = new JSONObject();
//                subJson.put("name", subEntry.getKey());
//                subJson.put("children", subEntry.getValue());
//
//                childrenJson.put(subEntry.getKey(), subJson);
//            }
//
//            jsonObject.put("children", childrenJson);
//            js.add(jsonObject);
//        }
//        System.out.println(js);
        // 使用 Stream API 进行分组
//        Map<String, Map<String, List<BranchSubTypeEntity>>> groupedProjects = javaList.stream()
//                .collect(Collectors.groupingBy(BranchSubTypeEntity::getParentBranchName,
//                        Collectors.groupingBy(BranchSubTypeEntity::getSonBranchName)));

        // 将分组后的数据转换成图片结构
        // 此处根据你的具体需求来处理 groupedProjects，将其转换成你需要的图片格式
        // 这里仅是一个示例输出
//        groupedProjects.forEach((parentBranch, sonBranchMap) -> {
//            System.out.println("Parent Branch: " + parentBranch);
//            sonBranchMap.forEach((sonBranch, projectsList) -> {
//                System.out.println("\tSon Branch: " + sonBranch);
//                projectsList.forEach(System.out::println);
//            });
//        });
//        System.out.println(javaList);
    }
}
